package com.example.controller;

import com.example.entity.Stu;
import com.example.repository.StuDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;


import java.util.List;

@Controller

public class StuController {
    @Autowired
    StuDao repository;

    @RequestMapping("/showAllStu")
    public String showAllStu(Model model){
        List<Stu> stus = repository.findAll();
        model.addAttribute("stus",stus);
        return "showAllStu";
    }
    @RequestMapping("/Stu_input")
    public String StuInput(){
        return "addStu";
    }
    @RequestMapping("/addStu")
    public String addStu(String name,double java,Model model){
        try{
            Stu stu = new Stu(name,java);
            repository.save(stu);
            List<Stu> stus = repository.findAll();
            model.addAttribute("stus",stus);
            return "showAllStu";
        }catch(Exception e){
            return "add_Fail";
        }
    }
    @RequestMapping("/DelStu/{id}")
    public String DelStu(@PathVariable Long id){
        repository.deleteById(id);
        return "redirect:/showAllStu";
    }

    @RequestMapping("/page")
    public String page(@PageableDefault(size=2) Pageable pageable,Model model){
        Page<Stu> stus=repository.findAll(pageable);
        model.addAttribute("stus",stus);
        return "stu_page";
    }
}
